package com.item.service.item;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.item.mapper.foodmapper;
import com.item.mapper.springsecuritymapper;
import com.item.mapper.usermapper;
import com.item.pojo.*;
import com.item.service.foodservice;
import com.item.utils.ItemCF;
import com.item.utils.RedisUtil;
import com.item.utils.UserCF;
import com.item.utils.computerrating;
import lombok.AllArgsConstructor;
import org.apache.ibatis.transaction.Transaction;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.chrono.ChronoLocalDateTime;
import java.util.*;
@Transactional
@Service
@AllArgsConstructor
public class foodserviceitem  implements foodservice {
    private foodmapper foodmapper;
    private RedisTemplate redisTemplate;
    private springsecuritymapper springsecuritymapper;
    private RedisUtil redisUtil;
private computerrating computerrating;
    @Override
    public List<MenuItem> getfood(String type) {
        List<MenuItem> menuItems = new ArrayList<>();

        return menuItems = foodmapper.getfood(type);
    }

    @Override
    public void insertto0rder(BigDecimal price, int id, int userid, int ammount) {
        BigDecimal allprice = price.multiply(BigDecimal.valueOf(ammount));
        Order order = new Order();
        order = foodmapper.findOrderByUserIdAndStatus(userid);
        if (order == null) {
            foodmapper.insertOrder(userid, allprice);
            order = foodmapper.findOrderByUserIdAndStatus(userid);
            System.out.println(id + order.getId());
            if (foodmapper.findOrderdeitalByItemIdAndOrderId(id, order.getId()) == null) {
                foodmapper.insertOrderDetail(order.getId(), id, ammount, price);
            } else {
                foodmapper.updateOrderDetailQuantity(ammount, order.getId(), id);

            }

        } else {
            foodmapper.updateOrder(userid, allprice);
            if (foodmapper.findOrderdeitalByItemIdAndOrderId(id, order.getId()) == null) {
                foodmapper.insertOrderDetail(order.getId(), id, ammount, price);
            } else {
                foodmapper.updateOrderDetailQuantity(ammount, order.getId(), id);

            }
        }
    }

    @Override
    public List<OrderDetailsResponse> getorder(int usderid) {
        Order order = foodmapper.findOrderByUserIdAndStatus(usderid);
        if (order == null) {
            return null;
        }
        List<OrderDetail> orderDetails = foodmapper.findOrderDetailsByOrderId(order.getId());

        List<OrderDetailsResponse> orderItems = new ArrayList<>();
        List<OrderDetailsResponse> orderItemlist = new ArrayList<>();
        for (OrderDetail detail : orderDetails) {
            // 根据菜品id查询菜品信息
            MenuItem menuItem = foodmapper.findMenuItemById(detail.getItemId());
            System.out.println(menuItem.getId());
            if (menuItem != null) {
                // 构建订单详情响应
                OrderDetailsResponse orderItem = new OrderDetailsResponse();
                orderItem.setItemName(menuItem.getItemname());
                orderItem.setPrice(menuItem.getPrice());
                orderItem.setQuantity(detail.getQuanntite());
                orderItem.setImageUrl(menuItem.getImageUrl());
                orderItem.setId(menuItem.getId());
                orderItems.add(orderItem);
            }
        }
        Set<String> processedItems = new HashSet<>(); // 创建一个集合用于保存已处理的菜名
        for (OrderDetailsResponse orderItem : orderItems) {
            if (!processedItems.contains(orderItem.getItemName())) { // 如果菜名没有被处理过
                processedItems.add(orderItem.getItemName()); // 将菜名添加到集合中
                OrderDetailsResponse response = new OrderDetailsResponse();
                int quanntity = foodmapper.findQuantiteByITEMNAME(orderItem.getItemName(), usderid);
                response.setItemName(orderItem.getItemName());
                response.setPrice(orderItem.getPrice());
                response.setImageUrl(orderItem.getImageUrl());
                response.setQuantity(quanntity);
                response.setId(orderItem.getId());
                orderItemlist.add(response);
            }
        }

        System.out.println("11111" + orderItemlist);
        return orderItemlist;
    }

    @Override
    public BigDecimal getorderamount(int userid) {

        Order order = foodmapper.findOrderByUserIdAndStatus(userid);
        BigDecimal price = foodmapper.updateOrderamount(order.getId());

        foodmapper.updateOrderprice(userid, price);
        return order.getTotalamount();
    }

    @Override
    public BigDecimal changeamountbycoupon(int userid, int couponid) {
        Order order = foodmapper.findOrderByUserIdAndStatus(userid);
        BigDecimal price = foodmapper.updateOrderamount(order.getId());
        BigDecimal price1= foodmapper.updateOrderamount(order.getId());
      Coupon coupon = foodmapper.getcouponByid(couponid);
        LocalDateTime now = LocalDateTime.now();
      if((coupon.getStartDate().isBefore(now)) && (coupon.getEndDate().isAfter(now))){
          System.out.println("in the 当前时间在优惠时间之间");
          BigDecimal discountValue = coupon.getDiscountValue();
          BigDecimal one = new BigDecimal(1);
          if(discountValue.compareTo(one) > 0){
              price = price.subtract(discountValue);
              BigDecimal discountValue2 = price1.subtract(price);
              if(discountValue2.compareTo(coupon.getMaximumSpend())>0){
                  price1=price1.subtract(coupon.getMaximumSpend());
                  foodmapper.updateOrderprice(userid, price1);
                  foodmapper.changestatuscoupon(couponid,userid);
                  order = foodmapper.findOrderByUserIdAndStatus(userid);
                  return order.getTotalamount();

              }else {

                  foodmapper.updateOrderprice(userid,price);
                  foodmapper.changestatuscoupon(couponid,userid);
                  order = foodmapper.findOrderByUserIdAndStatus(userid);
                  return order.getTotalamount();
              }

          }
          else {
              price=price.multiply(discountValue);
              BigDecimal discountValue2 = price1.subtract(price);
              if(discountValue2.compareTo(coupon.getMaximumSpend())>0){
                  price1=price1.subtract(coupon.getMaximumSpend());
                  foodmapper.updateOrderprice(userid, price1);
                  foodmapper.changestatuscoupon(couponid,userid);
                  order = foodmapper.findOrderByUserIdAndStatus(userid);
                  return order.getTotalamount();

              }else {

                  foodmapper.updateOrderprice(userid,price);
                  foodmapper.changestatuscoupon(couponid,userid);
                  order = foodmapper.findOrderByUserIdAndStatus(userid);
                  return order.getTotalamount();
              }

          }
        }
      else {
          System.out.println("not in the :当前时间不在优惠时间之间");
          return null;
      }


    }

    @Override
    public void deletOrderDetailByitemId(int itemId, int userid) {
        try {
            Order order = foodmapper.findOrderByUserIdAndStatus(userid);
            System.out.println(order.getId());
            System.out.println(itemId);
            foodmapper.deleteOrderDetail(order.getId(), itemId);
            getorderamount(userid);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Boolean ConfirmOrder(int userid) {
        try {
            if((String) redisTemplate.opsForValue().get("couponId")!=null){
                String couponstringid= (String) redisTemplate.opsForValue().get("couponId");
                int couponId= Integer.parseInt(couponstringid);

                String status=foodmapper.getcouponstatus(couponId,userid);
                if(status!=null&&status.equals("未使用")){
                    changeamountbycoupon(userid,couponId);
                }

                foodmapper.updateOrderstatus(userid);
                return true;
            }
            else {
                foodmapper.updateOrderstatus(userid);
                return true;
            }

        } catch (Exception e) {
            System.out.println(e);
            return false;
        }

    }

    @Override
    public boolean Modifysales(int itemId, int userid) {
        System.out.println(itemId);
        int quantity;
        try {
            Order order = foodmapper.findOrderByUserIdAndStatus(userid);
            quantity = foodmapper.getTotalQuantityByItemId(itemId, order.getId());
            foodmapper.updateSalesById(itemId, quantity);
            System.out.println("更新销量成功");
            return true;
        } catch (Exception e) {
            System.out.println("更新销量失败");
            return false;
        }

    }

    @Override
    public List<MenuItem> searchfood(String itemname) {
        if (itemname != null) {
            System.out.println("模糊查询菜品成功");
            return foodmapper.searchfood(itemname);

        } else {
            System.out.println("查询失败");
            return null;
        }
    }

    @Override
    public List<MenuItem> findspecialmenu(String type) {
        if (foodmapper.getfood(type) != null) {
            return foodmapper.getfood(type);
        } else {
            return null;
        }

    }

    @Override
    public Boolean Spikesmenu(int id, int userid, BigDecimal price, int ammount) {
        MenuItem menuItem = foodmapper.getmenu(id);
        Order order = new Order();
        if (menuItem.getQuantity() >= 1) {
            order = foodmapper.findallOrderByUserIdAndStatus(userid);
            if (order != null) {
                if (foodmapper.findOrderdeitalByItemIdAndOrderId(id, order.getId()) == null)
                {
                    foodmapper.Spikesmenu(id, menuItem.getVersion());
                    foodmapper.insertsepcialOrder(userid, price);
                    order = foodmapper.findSepcialOrderByUserIdAndStatus(userid);
                    foodmapper.insertOrderDetail(order.getId(), id, ammount, price);
                    this.ModifySpecialsales(id, userid);
                    return true;
                } else return false;
            } else {
                foodmapper.Spikesmenu(id, menuItem.getVersion());
                foodmapper.insertsepcialOrder(userid, price);
                order = foodmapper.findSepcialOrderByUserIdAndStatus(userid);
                foodmapper.insertOrderDetail(order.getId(), id, ammount, price);
                this.ModifySpecialsales(id, userid);
                return true;
            }


        } else {
            return false;
        }
    }

    @Override
    public Boolean SpikesmenuRedis(int itemid, int userid) {
        String itemname = "item_" + itemid;
        String itemorder = itemname + "_" + itemid;
        System.out.println(itemname);

        try {
            redisTemplate.watch(itemname);

            String itemamountStr = (String) redisTemplate.opsForValue().get(itemname);
            if (itemamountStr == null || itemamountStr.trim().isEmpty()) {
                System.out.println("No stock available");
                return false;
            }

            int itemamount = Integer.parseInt(itemamountStr);
            if (itemamount < 1) {
                System.out.println("Stock is empty");
                return false;
            }

            redisTemplate.multi();
            redisTemplate.opsForValue().decrement(itemname);
            redisTemplate.opsForSet().add(itemorder, String.valueOf(userid));
            redisTemplate.exec();
        } catch (Exception e) {

            System.out.println("Error occurred while processing spike menu: " + e.getMessage());
            return false;
        }

        return true;
    }

    @Override
    public Boolean ModifySpecialsales(int itemId, int userid) {
        System.out.println(itemId);
        int quantity;
        try {
            Order order = foodmapper.findSepcialOrderByUserIdAndStatus(userid);
            quantity = foodmapper.getTotalQuantityByItemId(itemId, order.getId());
            foodmapper.updateSalesById(itemId, quantity);
            System.out.println("更新销量成功");
            return true;
        } catch (Exception e) {
            System.out.println("更新销量失败");
            return false;
        }
    }

    @Override
    public List<itempack> finditempack() {
        try {
            List<itempack> itempacks = new ArrayList<>();
            itempacks = foodmapper.getitempack();
            return itempacks;
        } catch (Exception e) {
            System.out.println(e);
            return null;

        }


    }

    @Override
    public List<ItemComment> getcomment(int itemId) {
        try {
            List<ItemComment> itemComments = foodmapper.getcomment(itemId);
            return itemComments;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }

    @Override
    public List<ItemComment> getdowncomment(int id, int itemId) {
        try {
            List<ItemComment> comments = foodmapper.getdowncomment(id, itemId);
            return comments;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public User getuserdetail(int userId) {

        try {
            return foodmapper.finduserdetailByid(userId);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return null;
    }

    /**
     * 插入一条评论信息到数据库。
     *
     * @param comment 评论内容
     * @param rating  评论评分
     * @param pid     父级评论的ID，用于建立评论层级关系
     * @param userId  发表评论的用户ID
     * @param itemId  被评论的商品或服务ID
     *                该方法不返回任何值，但会通过打印信息反馈评论插入操作的成功或失败。
     */
    @Override
    public void insertcomment(String comment, double rating, int pid, int userId, int itemId) {
        // 尝试插入评论到数据库
        if (foodmapper.insertcomment(comment, rating, pid, userId, itemId)) {
            System.out.println("二级评论执行成功");

        } else {
            System.out.println("二级评论执行失败");
        }
    }

    /**
     * 完成指定用户的外卖订单。
     *
     * @param userId 用户的ID，用于标识特定的用户。
     *               该方法没有返回值。
     */
    @Override
    public void finshapipalyorder(int userId) {
        // 检查该用户是否存在未完成的特殊订单
        if (foodmapper.findSepcialOrderByUserIdAndStatus(userId) != null) {
            // 生成一个随机订单号
            String number = String.valueOf((int) ((Math.random() * 900000) + 100000));
            try {
                // 尝试使用生成的订单号完成该用户的订单
                foodmapper.finshapiplyorder(userId, number);
                redisUtil.set("number", number);
            } catch (Exception e) {
                // 记录异常信息
                e.printStackTrace();
                System.out.println(e);
            }
        }
    }

    @Override
    public List<OrderDetailsResponse> findordetailbyuserIdandnumber(int userId) {
        try {
            String number;
            try {
                number = (String) redisUtil.get("number");
            } catch (NumberFormatException e) {
                System.out.println("无法将字符串转换为整数: " + e.getMessage());
                return null;  // 或者处理异常情况
            }
            List<OrderDetail> orderDetails = foodmapper.findorderdetailByorderid(userId, number);
            List<OrderDetailsResponse> orderItems = new ArrayList<>();
            List<OrderDetailsResponse> orderItemlist = new ArrayList<>();
            for (OrderDetail detail : orderDetails) {
                // 根据菜品id查询菜品信息
                MenuItem menuItem = foodmapper.findMenuItemById(detail.getItemId());
                System.out.println(menuItem.getId());
                if (menuItem != null) {
                    // 构建订单详情响应
                    OrderDetailsResponse orderItem = new OrderDetailsResponse();
                    orderItem.setItemName(menuItem.getItemname());
                    orderItem.setPrice(menuItem.getPrice());
                    orderItem.setQuantity(detail.getQuanntite());
                    orderItem.setImageUrl(menuItem.getImageUrl());
                    orderItem.setId(menuItem.getId());
                    orderItems.add(orderItem);
                }
            }
            Set<String> processedItems = new HashSet<>(); // 创建一个集合用于保存已处理的菜名
            for (OrderDetailsResponse orderItem : orderItems) {
                if (!processedItems.contains(orderItem.getItemName())) { // 如果菜名没有被处理过
                    processedItems.add(orderItem.getItemName()); // 将菜名添加到集合中
                    OrderDetailsResponse response = new OrderDetailsResponse();
                    int quanntity = foodmapper.findQuantiteByitnameandnumber(orderItem.getItemName(), userId, number);
                    response.setItemName(orderItem.getItemName());
                    response.setPrice(orderItem.getPrice());
                    response.setImageUrl(orderItem.getImageUrl());
                    response.setQuantity(quanntity);
                    response.setId(orderItem.getId());
                    orderItemlist.add(response);
                }
            }

            System.out.println("22222" + orderItemlist);

            if (orderDetails.size() == 0) {
                System.out.println("该用户没有订单");
            }
            return orderItemlist;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return null;
    }

    @Override
    public BigDecimal findtotalamountByuseridandnumber(int userId) {
        String number;
        try {
            number = (String) redisUtil.get("number");

        } catch (NumberFormatException e) {
            System.out.println("无法将字符串转换为整数: " + e.getMessage());
            return null;  // 或者处理异常情况
        }
        try {
            return foodmapper.findtotalamountByuseridandnumber(userId, number);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            return null;

        }
    }

    @Override
    public int findorderidByuseridandnumber(int userId) {
        try {
            String number;
            try {
                number = (String) redisUtil.get("number");
            } catch (NumberFormatException e) {
                System.out.println("无法将字符串转换为整数: " + e.getMessage());
                return 0;  // 或者处理异常情况
            }
            return foodmapper.findorderidByuseridandnumber(userId, number);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return 0;
    }

    @Override
    public String findorderstatusByuseridandnumber(int userId) {
        try {
            String number;
            try {
                number = (String) redisUtil.get("number");
            } catch (NumberFormatException e) {
                System.out.println("无法将字符串转换为整数: " + e.getMessage());
                return null;  // 或者处理异常情况
            }
            return foodmapper.findorderstatusByuseridandnumber(userId, number);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return null;
    }

    @Override
    public List<Order> findorderByuserid(int userId) {
        try {
            return foodmapper.findorderByuserid(userId);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            return null;
        }

    }

    @Override
    public List<MenuItem> finditemlistByOrderId(int orderId) {
        try {
            return foodmapper.finditemlistByOrderId(orderId);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            return null;
        }

    }

    @Override
    public List<OrderDetailsResponse> findordetailbyorderId(int orderId) {
        try {

            List<OrderDetail> orderDetails = foodmapper.findorderdetailByorderId(orderId);
            List<OrderDetailsResponse> orderItems = new ArrayList<>();
            List<OrderDetailsResponse> orderItemlist = new ArrayList<>();
            for (OrderDetail detail : orderDetails) {
                // 根据菜品id查询菜品信息
                MenuItem menuItem = foodmapper.findMenuItemById(detail.getItemId());
                System.out.println(menuItem.getId());
                if (menuItem != null) {
                    // 构建订单详情响应
                    OrderDetailsResponse orderItem = new OrderDetailsResponse();
                    orderItem.setItemName(menuItem.getItemname());
                    orderItem.setPrice(menuItem.getPrice());
                    orderItem.setQuantity(detail.getQuanntite());
                    orderItem.setImageUrl(menuItem.getImageUrl());
                    orderItem.setId(menuItem.getId());
                    orderItems.add(orderItem);
                }
            }
            Set<String> processedItems = new HashSet<>(); // 创建一个集合用于保存已处理的菜名
            for (OrderDetailsResponse orderItem : orderItems) {
                if (!processedItems.contains(orderItem.getItemName())) { // 如果菜名没有被处理过
                    processedItems.add(orderItem.getItemName()); // 将菜名添加到集合中
                    OrderDetailsResponse response = new OrderDetailsResponse();
                    int quanntity = foodmapper.findQuantiteByorderId(orderItem.getItemName(), orderId);
                    response.setItemName(orderItem.getItemName());
                    response.setPrice(orderItem.getPrice());
                    response.setImageUrl(orderItem.getImageUrl());
                    response.setQuantity(quanntity);
                    response.setId(orderItem.getId());
                    orderItemlist.add(response);
                }
            }

            System.out.println("22222" + orderItemlist);

            if (orderDetails.size() == 0) {
                System.out.println("该用户没有订单");
            }
            return orderItemlist;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return null;
    }

    @Override
    public BigDecimal findtotalamountByorderId(int orderId) {

        try {
            return foodmapper.findtotalamountByorderId(orderId);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            return null;

        }
    }


    @Override
    public String findorderstatusByorderId(int orderId) {
        try {
            return foodmapper.findorderstatusByorderId(orderId);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return null;
    }

    @Override
    public List<Coupon> getcouponByuserId(int userId) {
        try {
            return foodmapper.getunusecouponByuserId(userId);
        }
        catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            return null;
        }

    }

    @Override
    public List<Coupon> getallcoupons() {
        try{

            System.out.println("优惠卷查询成功");
            return foodmapper.getallCoupons();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }

        return null;
    }

    @Override
    public List<Role> getallrole() {
       String username= (String) redisTemplate.opsForValue().get("username");
        try{

            System.out.println(" 角色查询成功");
            return springsecuritymapper.findByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return null;
    }

    @Override
    public Boolean getcoupons(int couponId) {
        try{
            LocalDateTime now = LocalDateTime.now();
            String userstringid= (String) redisTemplate.opsForValue().get("userid");
            int userid= Integer.parseInt(userstringid);
            if (foodmapper.getuserCouponByuserIdandcouponId(userid,couponId)==null){
                Coupon coupon=foodmapper.getcouponByid(couponId);
                if(coupon.getNumber()>0)
                {
                    if((coupon.getStartDate().isBefore(now)) && (coupon.getEndDate().isAfter(now))){
                        foodmapper.deletcoupon(couponId,coupon.getVersion(),coupon.getNumber());
                        foodmapper.insertuserCoupon(userid,couponId);
                        return true;
                    }else {
                        System.out.println("优惠券已经过期");
                        return false;
                    }

                }else {
                    System.out.println("优惠券已经领完了");
                    return false;
                }

            }else {
                System.out.println("该优惠券已经领取");
                return false;
            }


        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            return false;
        }

    }

   /**
    * 根据用户ID获取推荐的美食评论ID列表。
    *
    * @param userId 用户的唯一标识符。
    * @return 返回一个整数列表，包含根据用户兴趣推荐的评论ID。
    */
   @Override
   public List<Integer> getcommenditmeId(int userId) {
       // 从数据库获取所有美食评论
       List<ItemComment> itemComments = foodmapper.getallcomment();

       // 基于用户行为和评论内容，为当前用户生成推荐列表
       List<Integer> recommendations = UserCF.recommend(userId, itemComments);
       System.out.println(recommendations);
       return recommendations ;
   }

    @Override
    public List<MenuItem> getmenurecommendbyuserId(List<Integer> userId) {
try {
    if(!userId.isEmpty()){
        return foodmapper.getitemByuserrecommenduserId(userId);
    }
    else {
        return null;
    }

} catch (Exception e) {
    e.printStackTrace();
    System.out.println(e);
    return null;
}

    }
@Transactional
    @Override
    public Boolean insertorderdetailBypackItem(int userId,BigDecimal totalamount,int packId) {
       try{

           Order order = foodmapper.findorderByuseridandstatus(userId);
           if(order==null){
               foodmapper.insertitmepacktoOrder(totalamount,userId);
               order = foodmapper.findorderByuseridandstatus(userId);
               List<Integer> itemIdList = foodmapper.getitemIdBypackId(packId);
               for (Integer integer : itemIdList) {
                  MenuItem menuItem = foodmapper.getitemByitemId(integer);
                   foodmapper.insertorderdetail(order.getId(),menuItem.getId(),1,menuItem.getPrice());
                       foodmapper.updateSalesById(menuItem.getId(),1);

               }

           }else {
               return false;
           }
           return true;
       } catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }


    }

    @Override
    public List<MenuItem> getListmenuBypackId(int packId) {
       try{

          return foodmapper.getListmenuBypackId(packId);

       } catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }

    }

    @Override
    public List<Integer> getitemIdByrecomend(int itemId) {
        List<ItemComment> itemComments = foodmapper.getallcomment();

        List<Integer> itemList=ItemCF.recommend(itemId, itemComments);
        System.out.println( itemList);
        return itemList ;

    }

    @Override
    public List<MenuItem> menurecommendByitemId(List<Integer> itemId) {
       try {
           if(!itemId.isEmpty()){
               return foodmapper.getitemByuserrecommenditemId(itemId);
           }
           else {
               return null;
           }
    } catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }
    }

    @Override
    public List<MenuItem> menuListBysales() {
       try {
           return foodmapper.getmenudesc();
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }
    }

    @Override
    public List<Integer> menuidListByAveragerating() {
       try {

          List<ItemComment> itemComments= foodmapper.getallcomment();
          List<Integer>itemIdlist=computerrating.itemList(itemComments);
           System.out.println(itemIdlist);
          return itemIdlist;
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }
    }

    @Override
    public List<MenuItem> menuListByavagerItemList(List<Integer> itemIdList) {
        try {
            List<MenuItem> menuItemList =new ArrayList<>();
          itemIdList.forEach(itemId -> {
              if(foodmapper.getitemByitemId(itemId)!=null){
                  menuItemList.add(foodmapper.getitemByitemId(itemId));
              }
              if(foodmapper.getitemByitemId(itemId)==null){
                  System.out.println("该id不存在");
              }
          });
            return menuItemList;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
            return null;
        }

    }

    @Override
    public Boolean deletorderanorderdetail(int orderId) {
       try{
           if(orderId!=0){
               foodmapper.getorderdetailByorderId(orderId);
               List<OrderDetail>orderDetails=foodmapper.getorderdetailByorderId(orderId);
               if(orderDetails!=null){
                  orderDetails.forEach(orderDetail -> {
                      foodmapper.decreseitemsalas(orderDetail.getItemId(),orderDetail.getQuanntite());
                  });
               }else {
                   System.out.println("该订单没有订单详情 not have the orderdetail");
                   return false;
               }
               String number = String.valueOf((int) ((Math.random() * 900000) + 100000));

               foodmapper.deletorderByuseridandstatus(orderId,number);
               return true;
           }else {
               System.out.println("该订单不存在");
               return false;
           }

       } catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }

    }

    @Override
    public List<User> getAlluserlist() {
       try {
           return foodmapper.getalluser();
       } catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }

    }

    @Override
    public Boolean updatepassword(String username, String password) {
       try {
           User user = springsecuritymapper.getusername(username);
           if(user!=null){
               user.setPassword(password);
               foodmapper.updateuser(username,password);
               return true;
           }else {
               return false;
           }
       } catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }

    }

    @Override
    public Boolean updateuser(int id, String username, String email, String phone, String imageurl, int age) {
       try {
               foodmapper.updateuserByusernameByemailByageByphoneByimageurl(id,username,email,age,phone,imageurl);
               return true;
           } catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }
    }

    @Override
    public List<Role> getallRolemange() {
       try {
           return foodmapper.getallrole();
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }
    }
    public List<Role> getallroleByusername(String username) {

        try{
            System.out.println(" 角色查询成功");
            return springsecuritymapper.findByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }
        return null;
    }

    @Override
    public Boolean insertuserRoleByuseridandroleid(int userid, List<Integer> roleid) {
       List<Integer> roles=foodmapper.getallroleByuserid(userid);
       List<Integer> newroleid=new ArrayList<>();
           System.out.println("roles"+roles);
           roleid.forEach(id -> {
               if(!roles.contains(id)){
                   newroleid.add(id);
               }
               if(roles.contains(id)){
                   System.out.println("该角色已存在");
               }

       });
        System.out.println(newroleid);
       try {
           newroleid.forEach(role1 -> {
               foodmapper.insertuserRoleByuseridandroleid(userid,role1);
               System.out.println("插入成功");

           });
           return true;
       } catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }

    }

    @Override
    public Boolean updateUserstatus(int userid) {
       int banned=0;
      banned= foodmapper.finduserstatusByuserId(userid);
      if(banned==0){
          foodmapper.UpadteusertatusByuserId(userid,1);
          return true;
      }
      if(banned==1){
          foodmapper.UpadteusertatusByuserId(userid,0);
          return true;
      }
        return false;
    }

    @Override
    public List<MenuItem> getallmenuList() {
       try {
           return foodmapper.getmenuList();
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }

    }

    @Override
    public Boolean insertmenuBybakground(MenuItem menuItem) {
       try {
           foodmapper.insertMenuItem(menuItem.getItemname(),menuItem.getPrice(),menuItem.getDescription(),menuItem.getImageUrl(),menuItem.getQuantity(),menuItem.getType(),0);
           return true;
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }
    }

    @Override
    public MenuItem getmenuByid(int id) {
       try
       {
           return foodmapper.getitemByitemId(id);
       }
       catch (Exception e)
       {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }
    }

    @Override
    public Boolean updateitemByitem(MenuItem menuItem) {
       try {
           foodmapper.updateitemByitem(menuItem.getId(),menuItem.getItemname(),menuItem.getPrice(),menuItem.getDescription(),menuItem.getImageUrl(),menuItem.getQuantity(),menuItem.getType());
           return true;
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }

    }

    @Override
    public Boolean updateitemspecialPriceandtypeandquantityByitemId(MenuItem menuItem) {
       try {
           foodmapper.updateitemspecialPriceandtypeandquantityByitemId(menuItem.getId(),menuItem.getSpecialPrice(),menuItem.getType(),menuItem.getQuantity());
           return true;
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }

    }

    @Override
    public Boolean updateitemstatusByitemId(int itemId) {
       MenuItem menuItem=foodmapper.getitemByitemId(itemId);
       if(menuItem!=null){
           if(menuItem.getIsdelete()==0){
               foodmapper.updateitemstatusByitemid(itemId,1);
               return true;
           }
           if(menuItem.getIsdelete()==1){
               foodmapper.updateitemstatusByitemid(itemId,0);
               return true;
           }

       }
        return false;
    }

    @Override
    public Boolean updateitempriceByitemid(int itemId, BigDecimal price) {
       try {
           foodmapper.updateitempriceByitemid(itemId,price);
           return true;
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }

    }

    @Override
    public List<Order> getorderBybackground() {
       try {
           return foodmapper.getorderBybackground();
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }
    }

    @Override
    public Boolean updateorderstatusByorderId(int orderId, String status) {
       String status1=foodmapper.findorderstatusByorderId(orderId);
        String number1 = String.valueOf((int) ((Math.random() * 900000) + 100000));

        String number=null;
        try {
            number = (String) redisUtil.get("number");
        } catch (NumberFormatException e) {
            System.out.println("无法将字符串转换为整数: " + e.getMessage());
            return false;  // 或者处理异常情况
        }
         if(status1.contains(number)){
             try {
                 foodmapper.updateordersatusByorderId( orderId,status,number);
                 return  true;
             }catch (Exception e){
                 e.printStackTrace();
                 System.out.println(e);
                 return false;
             }


         }else {
             try {
                 foodmapper.updateordersatusByorderId(orderId,status,number1);
                 return  true;
             }catch (Exception e){
                 e.printStackTrace();
                 System.out.println(e);
                 return false;
             }
         }

    }

    @Override
    public Boolean diccountitemorice( BigDecimal Discount) {
       try {
           foodmapper.Updatediccountitemprice(Discount);
           return true;
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }


    }

    @Override
    public Boolean diccountitemoriceBytype(String type, BigDecimal Discount) {
       try {
           System.out.println(Discount);
           foodmapper.UpdatediccountitempriceBytype(Discount,type);
           return true;
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }

    }

    @Override
    public Boolean recoveritemorice() {
        String type = (String) redisTemplate.opsForValue().get("type");
        BigDecimal Discount = new BigDecimal((String) redisTemplate.opsForValue().get("Discount"));
        if(type.equals("全部"))
        {
            try {
                foodmapper.recoveritemprcie(Discount);
                return true;
            }
            catch (Exception e) {
                e.printStackTrace();
                System.out.println(e);
                return false;
            }
        }else {
            try {
                foodmapper.recoveritemprcieBytype(Discount,type);
                return true;
            }
            catch (Exception e) {
                e.printStackTrace();
                System.out.println(e);
                return false;
            }
        }
    }

    @Override
    public List<Coupon> getallcouponsBybackground() {
       try {
           return foodmapper.getallCouponsByground();
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }

    }

    @Override
    public Boolean insertcoupon(Coupon coupon) {
       try {
           foodmapper.insertcoupon(coupon.getDescription(),coupon.getDiscountValue(),coupon.getMinimumSpend(),coupon.getMaximumSpend(),coupon.getStartDate(),coupon.getEndDate(),coupon.getNumber(),coupon.getVersion(),coupon.getMember(),coupon.getIsdelete());
           return true;
       }catch (Exception e){
           e.printStackTrace();
           System.out.println(e);
           return false;
       }
    }

    @Override
    public Coupon getcouponByid(int id) {
       try {
           return foodmapper.getcouponByid(id);
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }

    }

    @Override
    public Boolean updatecoupon(Coupon coupon) {
       try {
           foodmapper.updatecouponBYid(coupon.getId(),coupon.getDescription(),coupon.getDiscountValue(),coupon.getMinimumSpend(),coupon.getMaximumSpend(),coupon.getStartDate(),coupon.getEndDate(),coupon.getNumber(),coupon.getMember(),coupon.getIsdelete());
           return true;
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }

    }

    @Override
    public Boolean setcouponTouser(int couponId, int userId) {
       try {
       UserCoupon coupon=foodmapper.getuserCouponByuserIdandcouponId(userId,couponId);
       if(coupon==null){
           foodmapper.insertUsercouponByuseridandcouponidandsatus(userId,couponId);
           return true;
       }else if(coupon.getStatus().equals("已使用")){
           foodmapper.updateUsercouponSatusByuseridandcouponidandsatus(userId,couponId);
           return true;
       }else {
           return false;
       }
       }catch (Exception e)
           {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }


    }

    @Override
    public List<User> finduserBYcouponId(int couponId) {
       try {
           return foodmapper.findUserBycouponId(couponId);
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }
    }

    @Override
    public Boolean deleteUsercouponByuserIdandcouponId(int couponId, int userId) {

       try {
           foodmapper.changestatuscoupon(couponId,userId);
           return true;
       }catch (Exception e)
           {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }
    }

    @Override
    public Boolean deletcouponByid(int id) {
     Coupon coupon=  foodmapper.getcouponByid(id);
       if(coupon.getIsdelete()==0){
           try {
               foodmapper.deletcouponByid(id,1);
               return true;
           }catch (Exception e)
           {
               e.printStackTrace();
               System.out.println(e);
               return false;
           }
       }else {
           try {
               foodmapper.deletcouponByid(id,0);
               return true;
           }catch (Exception e)
           {
               e.printStackTrace();
               System.out.println(e);
               return false;
           }
       }

    }

    @Override
    public List<ItemComment> getallcomment() {
       try {
           return foodmapper.getallcomment();
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }


    }

    @Override
    public Boolean insertcommentByidanditemid(String comment, int pid, int itemId) {
       try {
           foodmapper.updatecommentreplyByid(pid,1);
           foodmapper.insertcommentByidanditemid(comment,5.0,itemId,1,0,pid,0,2);
           return true;
       }
       catch (Exception e)
           {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }

    }

    @Override
    public Boolean updatecommentweightByid(int id,int itemId) {
        int maxweight=0;
        try {
            List<ItemComment> itemComments=foodmapper.getallcomment();
            for(ItemComment itemComment:itemComments)
            {
            if(itemComment.getItemId()==itemId){
                if(itemComment.getWeight()>maxweight){
                    maxweight=itemComment.getWeight();
                }
            }
            }
            foodmapper.updatecommentweightByid(id,maxweight+1);
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.out.println(e);
            return false;
        }
    }

    @Override
    public Boolean updatecommentisdeleteByid(int id) {
      ItemComment comment= foodmapper.getcommentByid(id);
      if(comment.getIsdelete()==0){
          try {
              foodmapper.updatecommentisdeleteByid(id,1);
              return true;
          }catch (Exception e)
          {
              e.printStackTrace();
              System.out.println(e);
              return false;
          }
      }else {
          try {
              foodmapper.updatecommentisdeleteByid(id,0);
              return true;
          }
          catch (Exception e)
          {
              e.printStackTrace();
              System.out.println(e);
              return false;
          }
      }
    }

    @Override
    public List<itempack> getallitempackBybackground() {
       try {
           return foodmapper.getallitempackBybackground();
       }
       catch (Exception e) {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }


    }

    @Override
    public Boolean insertitempackBybakground(String description, String imageUrl) {

       try {
           foodmapper.insertitempackBybakground(description,0,imageUrl,0);
           return true;
       }catch ( Exception e){
           e.printStackTrace();
           System.out.println(e);
           return false;
       }
    }

    @Override
    public Boolean updateitempackdescriptionByid(int id, String description, String imageUrl) {
       try {
           foodmapper.updateitempackdescriptionByid(id,description,imageUrl);
           return true;
       }
       catch (Exception e)
           {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }

    }

    @Override
    public BigDecimal getallpriceBypackId(int packId) {
       BigDecimal allprice= BigDecimal.valueOf(0);
       try {
          List<MenuItem> menuItems=foodmapper.getListmenuBypackId(packId);
          for(MenuItem menuItem:menuItems)
          {
              allprice=menuItem.getPrice().add(allprice);
          }
          return allprice;
       }
       catch (Exception e)
       {
           e.printStackTrace();
           System.out.println(e);
           return null;
       }
    }

    @Override
    public Boolean deletepackitemItemByitemIdandpackId(int itemId, int packId) {
       try {
           foodmapper.deletepackitemItemByitemIdandpackId(itemId,packId);
           return true;
       }
       catch (Exception e)
       {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }
    }

    @Override
    public Boolean insertpackitemItemByitemIdandpackId(int itemId, int packId) {
       try {
           foodmapper.insertpackitemItemByitemIdandpackId(itemId,packId);
           return true;
       }
       catch (Exception e)
       {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }
    }

    @Override
    public Boolean updateitempackallpriceByid(int id, BigDecimal price) {
       try {
           foodmapper.updateitempackallpriceByid(id,price);
           return true;
       }
       catch (Exception e)
       {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }
    }

    @Override
    public Boolean updeteitempackallpriceByaccountandid(int id,  BigDecimal account) {
       List<MenuItem> menuItems=foodmapper.getListmenuBypackId(id);
       int number=1;
       BigDecimal allprice=BigDecimal.valueOf(0);
       try {
           for (MenuItem menuItem:menuItems)
           {
               allprice=menuItem.getPrice().add(allprice);
           }
           if(account.compareTo(BigDecimal.valueOf(number))>0){
               allprice=allprice.subtract(account);
           }
           else {
               allprice=allprice.multiply(account);
           }
           foodmapper.updateitempackallpriceByid(id,allprice);
           return true;


       }
       catch (Exception e)
       {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }

    }

    @Override
    public Boolean updateallitempackallpriceByaccountandid( BigDecimal account) {
       List<itempack> itempacks=foodmapper.getitempack();
       try{
           for (itempack itempack:itempacks)
       {
           int number=1;
           BigDecimal allprice=BigDecimal.valueOf(0);
           List<MenuItem> menuItemList=foodmapper.getListmenuBypackId(itempack.getId());
           for (MenuItem menuItem:menuItemList)
           {
               allprice=menuItem.getPrice().add(allprice);
           }
           if(account.compareTo(BigDecimal.valueOf(number))>0){
               allprice=allprice.subtract(account);

           }
           else {
               allprice=allprice.multiply(account);
           }
           foodmapper.updateitempackallpriceByid(itempack.getId(),allprice);
       }
           return true;
       }catch (Exception e)
           {
           e.printStackTrace();
           System.out.println(e);
           return false;
       }



    }

    @Override
    public Boolean updateitempackisdeleteByid(int id) {
       itempack itempack=foodmapper.getitempackByid(id);
       if(itempack.getIsdelete()==0)
       {
           try {
               foodmapper.updateitempackisdeleteByid(id,1);
               return true;
           }catch (Exception e)
           {
               e.printStackTrace();
               System.out.println(e);
               return false;
           }
       }
       else {
           try {
               foodmapper.updateitempackisdeleteByid(id,0);
              return true;
          }catch (Exception e){
               e.printStackTrace();
               System.out.println(e);
               return false;
           }
       }

    }

    @Override
    public BigDecimal gettaldayorderaomunt() {
       BigDecimal totalamount= BigDecimal.valueOf(0);
       List<Order> orders=foodmapper.gettodayOrderList();
       try {
           if(orders!=null){
               for (Order order : orders) {
                   totalamount=totalamount.add(order.getTotalamount());
               }
               return totalamount;
           }else {
               return null;
           }
       }catch (Exception e){
           e.printStackTrace();
           System.out.println(e);
           return null;
       }

    }

    @Override
    public BigDecimal getyesterdayorderaomunt() {
       List<Order>orders=foodmapper.getyesterdayOrderList();
       BigDecimal totalamount=BigDecimal.valueOf(0);
       try {
           if(orders!=null){
               for (Order order:orders)
               {
                   totalamount=totalamount.add(order.getTotalamount());
               }
               return totalamount;
           }else {
               return null;
           }
       }catch (Exception e){
           e.printStackTrace();
           System.out.println(e);
           return null;
       }

    }

    @Override
    public BigDecimal getbetterOrderpercent() {
        List<Order>todayOderList=foodmapper.gettodayOrderList();
        List<Order>yesterdayOrderList=foodmapper.getyesterdayOrderList();
        BigDecimal todayamount=BigDecimal.valueOf(0);
        BigDecimal yesdayamount=BigDecimal.valueOf(0);
        BigDecimal betterpercent=BigDecimal.valueOf(0);
        try {
            if(yesterdayOrderList!=null && todayOderList!=null){
                for (Order order:todayOderList)
                {
                    todayamount=todayamount.add(order.getTotalamount());
                }
                for (Order order:yesterdayOrderList)
                {
                    yesdayamount=yesdayamount.add(order.getTotalamount());
                }
                betterpercent=todayamount.subtract(yesdayamount).divide(yesdayamount,2,BigDecimal.ROUND_HALF_UP);
                return betterpercent;

            }else {
                return null;
            }

        }
        catch (Exception e){
            e.printStackTrace();
            System.out.println(e);
            return null;

        }
    }

    @Override
    public List<MenuItem> menulistBysalsasLimteten() {
        try {
            List<MenuItem> menuItems=foodmapper.getTopTenMenuItemsBySales();
            return menuItems;
        }
        catch (Exception e){
            e.printStackTrace();
            System.out.println(e);
            return null;
        }


    }

    @Override
    public List<ItemComment> itemcommentListByuserId(int userId) {
       try {
           List<ItemComment> itemComments=foodmapper.itemcommentListByuserId(userId);
           return itemComments;
       }
       catch (Exception e){
           e.printStackTrace();
           System.out.println(e);
           return null;
       }
    }

    @Override
    public List<ItemComment> getitemcommentByuserIdandpid( int pid) {
       try {
           List<ItemComment> itemComments=foodmapper.getmycommentreplyByuseridandpid(pid);
           return itemComments;
       }
       catch (Exception e){
           e.printStackTrace();
           System.out.println(e);
           return null;
       }
    }

    @Override
    public Coupon getbestcoupon(BigDecimal price,int userId) {
      BigDecimal oldprice=price;
     Coupon coupons=new Coupon();
      BigDecimal diccountprice=BigDecimal.valueOf(0);
        BigDecimal dicountprice1=BigDecimal.valueOf(0);
      int number=0;
      int number1=1;
        List<Coupon> couponList=foodmapper.getunusecouponByuserId(userId);
        System.out.println(couponList);
        try {
            if(couponList!=null){
                for (Coupon coupon : couponList) {
              BigDecimal minmumspend= BigDecimal.valueOf(coupon.getMinimumSpend());
                    if(oldprice.subtract(minmumspend).compareTo(BigDecimal.valueOf(number))>0){

                        if(coupon.getDiscountValue().compareTo(BigDecimal.valueOf(number1))>0){
                            diccountprice=coupon.getDiscountValue();
                        }else {
                            diccountprice=price.subtract(price.multiply(coupon.getDiscountValue()));
                            if(diccountprice.compareTo(coupon.getMaximumSpend())>0){
                                diccountprice=coupon.getMaximumSpend();
                            }
                        }

                        if(diccountprice.compareTo(dicountprice1)>0){
                            dicountprice1=diccountprice;
                            coupons=coupon;
                        }


                    }
                }
                System.out.println(dicountprice1);
                return coupons;
            }else {
                return null;
            }

        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e);
            return null;
        }
    }

    @Override
    public Boolean deleteorderandorderDetailByuserId(int userId) {
        Order order=foodmapper.findOrderByUserIdAndStatus(userId);
        try {
            if(order!=null){
                foodmapper.deleteorderdetailByorderId(order.getId());
                foodmapper.deleteorderByuserIdandStatus(userId);
                return true;
            }else {
                return false;
            }
        }
        catch (Exception e){
            e.printStackTrace();
            System.out.println(e);
            return false;
        }
    }


}
